package com.p2p.auth.controller.api.crm;

import com.octo.captcha.service.CaptchaServiceException;
import com.p2p.auth.common.base.BaseCtrl;
import com.p2p.auth.common.base.JsonResult;
import com.p2p.auth.common.base.ProcessAPI;
import com.p2p.auth.common.base.ResultCode;
import com.p2p.auth.controller.Routes;
import com.p2p.auth.domain.dto.login.ChangePwdDTO;
import com.p2p.auth.domain.dto.login.ForgetPwdDTO;
import com.p2p.auth.domain.dto.user.LoginRequestDTO;
import com.p2p.auth.domain.dto.visitor.VisitorResponseDTO;
import com.p2p.auth.domain.entity.Visitor;
import com.p2p.auth.exceptions.SystemException;
import com.p2p.auth.exceptions.ValidateException;
import com.p2p.auth.service.ImageCaptchaService;
import com.p2p.auth.service.lifeCycle.VisitorUtils;
import com.p2p.auth.service.remote.ISms;
import com.p2p.auth.service.repository.VisitorRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.annotations.common.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lipei on 2017/6/5.
 */
@RestController
@EnableAutoConfiguration
@Api(value="用户登录API", description = "用户登录")
public class CrmLoginCtrl extends BaseCtrl {

    public static final String PHONE_CODE_LOGIN_TYPE = "PHONE_CODE_LOGIN";


    public static final String PASSWORD_LOGIN_TYPE = "PASSWORD_LOGIN";


    @Autowired
    private VisitorRepository visitorRepository;

    @Autowired
    private ISms smsRepository;


    @ApiOperation(value="用户登录" , notes = "输入手机号和密码进行登录" , produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(name = "req" , value="用户姓名和密码", required = true , dataType = "LoginRequestDTO")
    @RequestMapping(value = Routes.CRM_LOGIN, method = RequestMethod.POST)
    public JsonResult checkBalance(HttpServletRequest request,  @RequestBody LoginRequestDTO req) {
        ProcessAPI api = (result, validate) -> {
            if (req == null || StringHelper.isEmpty(req.getPhoneNum())) {
                result.setResultCode(ResultCode.PARAM_ERROR.getCode());
                result.setMsg("账户名为空，此次登陆失败");
                logger.error("请求信息参数错误。");
                return;
            }

            if (req == null || StringHelper.isEmpty(req.getPwd())) {
                result.setResultCode(ResultCode.PARAM_ERROR.getCode());
                result.setMsg("密码为空，此次登陆失败");
                logger.error("请求信息参数错误。");
                return;
            }

//            if (req == null || StringHelper.isEmpty(req.getLoginType())) {
//                result.setResultCode(ResultCode.PARAM_ERROR.getCode());
//                result.setMsg("登陆类型为空，此次登陆失败");
//                logger.error("请求信息参数错误。");
//                return;
//            }


//            if(req.getLoginType() != null && req.getLoginType().equals(PHONE_CODE_LOGIN_TYPE)){
//
//                if (StringHelper.isEmpty(req.getMsgCode())) {
//                    result.setResultCode(ResultCode.PARAM_ERROR.getCode());
//                    result.setMsg("短信验证码为空，此次登陆失败");
//                    logger.error("请求信息参数错误。");
//                    return;
//                }
//                JsonResult jsonResult = smsRepository.validateCode(req.getPhoneNum(), req.getMsgCode());
//
//                logger.info("jsonResult = {}", jsonResult);
//
//                if ( jsonResult == null || !jsonResult.getResultCode().equals(ResultCode.SUCC.getCode())) {
//                    result.setResultCode(ResultCode.PARAM_ERROR.getCode());
//                    result.setMsg("验证码错误，请重试");
//                    return;
//                }
//            }else if(req.getLoginType().equals(PASSWORD_LOGIN_TYPE)){
//                if (StringHelper.isEmpty(req.getVerifyCode())) {
//                    result.setResultCode(ResultCode.PARAM_ERROR.getCode());
//                    result.setMsg("图形证码为空，此次登陆失败");
//                    logger.error("请求信息参数错误。");
//                    return;
//                }
//                String inputVerifySource = validate.checkAndPrepare("verifySource", req.getVerifySource());
//                String inputVerifyCode = validate.checkAndPrepare("verifyCode", req.getVerifyCode());
//                validateCaptcha(inputVerifySource, inputVerifyCode);
//            }

            String phoneNum = req.getPhoneNum();

            String pwd = req.getPwd();

            Visitor visitor = visitorRepository.findByVisitorPhoneNum(phoneNum);
            if(visitor == null){
                result.setResultCode(ResultCode.USER_NOT_EXIST.getCode());
                result.setMsg(ResultCode.USER_NOT_EXIST.getMsg());
                return;
            }else if(StringHelper.isEmpty(visitor.getPassword()) || visitor.getPassword().equals(pwd) == false){
                result.setResultCode(ResultCode.USER_PASS_ERROR.getCode());
                result.setMsg(ResultCode.USER_PASS_ERROR.getMsg());
                return;
            }else {
                VisitorResponseDTO visitorResp = VisitorUtils.copyToDTO(visitor);
                result.setResult(visitorResp);
                result.setResultCode(ResultCode.SUCC.getCode());
            }
        };

        return api.process(request);
    }


    @ApiOperation(value = "修改密码", notes = "修改密码", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.CRM_CHANGE_PWD, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult changePasswordForPost(HttpServletRequest request, @RequestBody ChangePwdDTO dto, @PathVariable String phoneNum) {

        ProcessAPI api = (resp, validate) -> {

            String inputPhoneNum = validate.checkAndPrepare("phoneNum", phoneNum);
            String captchaId = validate.checkAndPrepare("verifySource", dto.getVerifySource());
            String response = validate.checkAndPrepare("verifyCode", dto.getVerifyCode());

            Visitor visitor = visitorRepository.findByVisitorPhoneNum(phoneNum);

            if(visitor == null){
                resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
                resp.setMsg("用户不存在，请重试");
                return;
            }

            //验证图形验证码
            validateCaptcha(captchaId, response);
            String newPwd = validate.checkAndPrepare("pwd", dto.getPwd());
            visitor.setPassword(newPwd);
            visitorRepository.saveAndFlush(visitor);
            VisitorResponseDTO visitorResponseDTO = VisitorUtils.copyToDTO(visitor);
            resp.result = visitorResponseDTO;
        };

        return api.process(request);
    }

    @ApiOperation(value = "忘记密码", notes = "忘记密码", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.CRM_FORGET_PWD, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult forgetPasswordForPost(HttpServletRequest request, @RequestBody ForgetPwdDTO dto, @PathVariable String phoneNum) {

        ProcessAPI api = (resp, validate) -> {

            String inputPhoneNum = validate.checkAndPrepare("phoneNum", phoneNum);
            String inputPhoneCode = validate.checkAndPrepare("verifyCode", dto.getVerifyCode());

            validate.checkAndPrepare("pwd", dto.getPwd());


            Visitor visitor = visitorRepository.findByVisitorPhoneNum(phoneNum);

            if(visitor == null){
                resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
                resp.setMsg("用户不存在，请重试");
                return;
            }

            //短信验证码
            JsonResult msgCodeCheckJsonResult = smsRepository.validateCode(phoneNum, dto.getVerifyCode());

            logger.info("jsonResult = {}", msgCodeCheckJsonResult);

            if ( msgCodeCheckJsonResult == null || !msgCodeCheckJsonResult.getResultCode().equals(ResultCode.SUCC.getCode())) {
                resp.setResultCode(ResultCode.PARAM_ERROR.getCode());
                resp.setMsg("验证码错误，请重试");
                return;
            }
            String newPwd = validate.checkAndPrepare("pwd", dto.getPwd());
            visitor.setPassword(newPwd);
            visitorRepository.saveAndFlush(visitor);
            VisitorResponseDTO visitorResponseDTO = VisitorUtils.copyToDTO(visitor);
            resp.result = visitorResponseDTO;
        };

        return api.process(request);
    }

    //验证图形验证码
    private void validateCaptcha(String captchaId, String response) {
        //验证图形验证码
        try {
            Boolean isResponseCorrect = Boolean.FALSE;
            isResponseCorrect = ImageCaptchaService.getInstance().validateResponseForID(captchaId, response);
            if (isResponseCorrect.equals(Boolean.FALSE)) {
                throw new ValidateException("图形验证码输入错误");
            }
        } catch (CaptchaServiceException e) {
            //should not happen, may be thrown if the id is not valid
            logger.error(e.getMessage());
            throw new SystemException("图形验证码已经失效");
        }
    }
}
